package org.xiaojl.modules.sys.controller;

import java.io.File;

import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.xiaojl.common.Constants;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.dwz.DwzAjax;
import org.xiaojl.dwz.PageBean;
import org.xiaojl.dwz.PageParam;
import org.xiaojl.modules.sys.entity.SysPicture;
import org.xiaojl.modules.sys.service.SysPictureService;
import org.xiaojl.utils.ToolUtil;

/**
 * <p>
 * 图片 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-09-07
 */
@Controller
@RequestMapping("/sys/sysPicture")
public class SysPictureController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(SysPictureController.class);
	private static final String basePagePath = "sys/picture/";
	
	@Autowired
	private SysPictureService sysPictureService;
	
	/**
	 * 查询数据，进入列表页面
	 */
	@RequiresPermissions("sys/sysPicture/list")
	@RequestMapping("/list")
	public ModelAndView list(PageParam pageParam, SysPicture entity, Model model){
		try {
			PageBean<SysPicture> pageBean = this.selectListPage(pageParam, entity, sysPictureService);
			
			model.addAttribute("pageBean", pageBean);
			model.addAttribute("pageParam", pageParam);
			model.addAttribute("entity", entity);
			
			return operatePage(basePagePath+"list",model);
		} catch (Exception e) {
			log.error("查询列表数据出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 转到添加页面 
	 */
	@RequiresPermissions("sys/sysPicture/add")
	@RequestMapping("/addUI")
	public ModelAndView addUI(Model model) {
		try {
			return operatePage(basePagePath+"add",model);
			
		} catch (Exception e) {
			log.error("进入添加页面出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	@RequestMapping("/upload")
	public ModelAndView upload(@RequestParam(value = "file") MultipartFile file, DwzAjax dwz){
		try {
			if (file!=null) {// 判断上传的文件是否为空
				SysPicture pic = new SysPicture();
				String path=null;// 文件路径
				String type=null;// 文件类型
				String fileName=file.getOriginalFilename();// 文件原名称
				log.debug("上传的文件原名称:"+fileName);
				// 判断文件类型
				type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
				if (type!=null) {// 判断文件类型是否为空
					if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
						// 项目在容器中实际发布运行的根路径
						String realPath=request.getSession().getServletContext().getRealPath("/");
						// 自定义的文件名称
						String trueFileName= Constants.IMG_SAVE_PATH + ToolUtil.getUid()+"."+type;
						// 设置存放图片文件的路径
						path=realPath+trueFileName;
						log.debug("存放图片文件的路径:"+path);
						// 转存文件到指定的路径
						file.transferTo(new File(path));
						log.debug("文件成功上传到指定目录下");
						
						pic.setName(fileName);
						pic.setType(type);
						pic.setSavePath(trueFileName);
						pic.setSourcePath("本地上传");
						
						sysPictureService.insert(pic);
						
					}else{
						return operateError("只能选择jpg、png、gif的图片文件");
					}
				}else{
					return operateError("只能选择jpg、png、gif的图片文件");
				}
				
			}else{
				log.info("文件为空！");
				return operateError("请选择想要上传的图片文件");
			}
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("上传图片出现异常:", e);
			return operateError("保存数据失败");
		}
	}
	
	/**
	 * 转到修改页面 .
	 */
	@RequiresPermissions("sys/sysPicture/edit")
	@RequestMapping("/editUI")
	public ModelAndView editUI(Model model, Long id) {
		try {
			SysPicture entity = sysPictureService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("获取数据失败");
			}

			model.addAttribute("entity",entity);
			return operatePage(basePagePath+"edit",model);
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:id="+id, e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 保存修改后的信息 .
	 * 
	 */
	@RequiresPermissions("sys/sysPicture/edit")
	@RequestMapping("/edit")
	public ModelAndView edit(@Valid SysPicture entity, BindingResult result, DwzAjax dwz) {
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			Long id = entity.getId();
			SysPicture oldObj = sysPictureService.selectById(id);
			if (ToolUtil.isEmpty(oldObj)) {
				return operateError("无法获取要修改的数据");
			}
			
			/** 数据唯一性校验逻辑*/
			
			
			//更新数据库
			sysPictureService.updateById(entity);
			
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("保存修改数据出现异常:", e);
			return operateError("保存失败");
		}
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("sys/sysPicture/delete")
	@RequestMapping("/delete")
	public ModelAndView delete(String ids, DwzAjax dwz) {
		try {
			if(ToolUtil.isEmpty(ids)){
				return operateError("请选择要删除的记录ID");
			}
			String[] idArray = ids.split(",");
			for(int i=0;i<idArray.length;i++){
				String id = idArray[i];
				SysPicture entity = sysPictureService.selectById(Long.parseLong(id));
				if (ToolUtil.isEmpty(entity)) {
					return operateError("ID=["+id+"]无法获取要删除的数据");
				}
				
				sysPictureService.deleteById(Long.parseLong(id));
			}
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("删除出现异常:ids="+ids, e);
			return operateError("删除失败");
		}
	}
	
}
